import styles from './index.less';
import logo from '@/images/index_logo.png';
import * as React from 'react';
import request from '@/http';

export default (props) => {
  let data = {};
  try{
    data = JSON.parse(window.localStorage.getItem('loginParams')||"");
  }
  catch (e) {

  }

  const [loginParams, setLoginParams] = React.useState<any>(data);
  console.log(loginParams.name);
  const btOnClick = () => {
    if (loginParams.name === undefined) {
      const data2 = { name:"tony",password:"123456"};
      setLoginParams( data2);
      window.localStorage.setItem('loginParams',JSON.stringify(data2))
    }

    request.get('/api/getUserById?id=1').then((result) => {
      console.log(result);
      const user = result.data;
      user.id = 1;
      user.userName = `${user.userName}-${new Date()}`;
      return request.post('/api/addOrUpdateUser', user);
    }).catch((error) => {
      console.log(error);
    });
  };
  const BASE_URL = '/service';
  const btOnClick2 = () => {
    fetch(BASE_URL + '/api/getUserById?id=1', {
      method: 'GET',
      cache: 'no-cache',
    })
      .then(function(response) {
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }
        return response.json();
      })
      .then(function(result) {
        console.log(result);
        if (!result.success) {
          throw new Error(result.message);
        }
        const user = result.data;
        user.id = 1;
        user.userName = `${user.userName}-${new Date()}`;
        return fetch(BASE_URL + '/api/addOrUpdateUser', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(user),
        });
      }).then((response) => {
      return response.json();
    }).then((result) => {
      console.log(result);
      if (!result.success) {
        throw new Error(result.message);
      }
    })
      .catch((error) => {
        console.log(error);
      });
  };

  return (
    <div className={styles.loginMain}>
      <img alt='首页' src={logo}/>
      <h1 className={styles.title}>Page index1,user name:{loginParams.name}</h1>
      <button onClick={btOnClick}>click me</button>
      <div>next:{props.children}</div>
    </div>
  );
}
